import com.googlecode.linkmein.domain.Employees
import com.googlecode.linkmein.domain.Result
import com.googlecode.linkmein.domain.Results
import com.googlecode.linkmein.domain.YIM
import com.googlecode.linkmein.service.FetchEmployeeService
import grails.converters.JSON
import javax.servlet.http.HttpServletResponse

class YahooController {
    FetchEmployeeService fetchEmployeeService
    def allowedMethods = [invite: 'POST', login: 'POST', index: 'GET', friends: 'GET']

    def beforeInterceptor = {
        if (!session.getAttribute("gmail")) {
            flash["error"] = "Please login with your google account and make sure your google account is in our list."
            redirect(uri: "/error.gsp")
            return false
        }
    }

    def login = {
        YIM yahoo = YIM.get(params.name, params.password);
        Result result = yahoo.login();
        if (result.isSuccess()) {
            session.setAttribute("yim", yahoo);
            redirect(controller: 'workmates', action: index)
        } else {
            render(view: 'index')
        }
    }

    def invite = {
        YIM yahoo = session.getAttribute("yim")
        if (yahoo == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, 'Not logged in')
            return;
        }
        Employees employees = fetchEmployeeService.getEmployees()
        Result result = yahoo.inviteFriend(employees.findByYahooId(params.id))
        if (result.isSuccess()) {
            response.sendError(HttpServletResponse.SC_OK, 'added successful');
        } else {
            response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, 'failed to add');
        }
    }

    def friends = {
        YIM yahoo = session.getAttribute("yim")
        if (yahoo == null) {
            render contentType: 'text/plain', text: '[]'
        } else {
            render contentType: 'text/plain', text: yahoo.getFriends() as JSON
        }
    }

    def index = {
        render(view: 'index')
    }

    def groupAll = {
        YIM yahoo = session.getAttribute("yim")
        if (yahoo == null) {
            response.sendError(HttpServletResponse.SC_UNAUTHORIZED, 'Not logged in')
            return;
        }
        Employees employees = fetchEmployeeService.getEmployees()
        Results results = yahoo.inviteAndRegroupFriends(employees)
        render contentType: 'text/plain', text: results
    }
}
